import React, { useState, useEffect } from "react";
import styles from "./index.module.less";
import SvgIcon from "@components/SvgIcon";
import { emojiListCommon, emojiListVip } from "./emojiList";
import { Scrollbars } from "react-custom-scrollbars-2";
import { connect } from "react-redux";
import { selectEmojiInfo, recordCurrentRange } from "@redux/actions02";
import editStyles from "../inputMain/index.module.less";
import { addSession, findSession } from "@depjs/storage";
import socket from "@depjs/socketClient";
import { profile } from "@depjs/storage";
import { useParams } from "react-router-dom";

// 使用过的表情最多展示个数
const MAX_CONTAINS = 8;

const InputHead = (props) => {
    const { selectEmojiInfo, currentRange } = props;
    const { id } = useParams();

    const [isShowEmoji, setIsShowEmoji] = useState(false);
    const [tabKey, setTabKey] = useState(0);
    const [emojiUsedList, setEmojiUsedList] = useState([]);

    const sendEmoji = (src) => {
        const edit = document.querySelector(`.${editStyles.edit}`);
        edit.focus();
        const img = document.createElement("img");
        img.src = src;
        img.classList.add("emoji_img");
        const selection = window.getSelection();
        const range = currentRange ?? selection.getRangeAt(0);
        range.insertNode(img);
        range.collapse();
        selection.removeAllRanges();
        selection.addRange(range);
    };

    useEffect(() => {
        document.onclick = function () {
            setIsShowEmoji(false);
        };
    }, []);

    useEffect(() => {
        setEmojiUsedList(findSession("emojiRecord")?.record || []);
    }, []);

    return (
        <div className={styles.input_head}>
            <div className={styles.left}>
                <div
                    className={styles.expression}
                    title="表情"
                    onClick={(e) => {
                        e.stopPropagation();
                        setIsShowEmoji(true);
                    }}
                >
                    <SvgIcon font="icon-biaoqing" />
                </div>
                <div
                    className={styles.emoticon}
                    style={{ display: isShowEmoji ? "" : "none" }}
                    onClick={(e) => {
                        e.stopPropagation();
                    }}
                >
                    <div className={styles.emoji_wrap}>
                        <div
                            className={styles.emoji_main1}
                            style={{ display: tabKey === 0 ? "" : "none" }}
                        >
                            <Scrollbars autoHide>
                                <p className={styles.title}>最近使用</p>
                                <ul className={styles.emoji_ul}>
                                    {emojiUsedList.map((item) => (
                                        <li
                                            key={item.id}
                                            title={item.name}
                                            onClick={() => {
                                                setIsShowEmoji(false);
                                                selectEmojiInfo(item);
                                                sendEmoji(item.url);
                                            }}
                                        >
                                            <img
                                                src={item.url}
                                                alt={item.name}
                                            />
                                        </li>
                                    ))}
                                </ul>
                                <p className={styles.title}>全部表情</p>
                                <ul className={styles.emoji_ul}>
                                    {emojiListCommon.map((item) => (
                                        <li
                                            key={item.id}
                                            title={item.name}
                                            onClick={() => {
                                                setIsShowEmoji(false);
                                                selectEmojiInfo(item);
                                                sendEmoji(item.url);
                                                const data = {
                                                    ...item,
                                                    date: Date.now(),
                                                };
                                                const isExist =
                                                    emojiUsedList.some(
                                                        (_item) =>
                                                            _item.id === item.id
                                                    );
                                                if (
                                                    emojiUsedList.length === 0
                                                ) {
                                                    addSession(
                                                        { record: [data] },
                                                        "emojiRecord"
                                                    );
                                                    setEmojiUsedList([data]);
                                                } else if (
                                                    emojiUsedList.length <
                                                    MAX_CONTAINS
                                                ) {
                                                    if (!isExist) {
                                                        addSession(
                                                            {
                                                                record: [
                                                                    data,
                                                                    ...emojiUsedList,
                                                                ],
                                                            },
                                                            "emojiRecord"
                                                        );
                                                        setEmojiUsedList([
                                                            data,
                                                            ...emojiUsedList,
                                                        ]);
                                                    } else {
                                                        const other =
                                                            emojiUsedList.filter(
                                                                (_item) =>
                                                                    _item.id !==
                                                                    item.id
                                                            );
                                                        addSession(
                                                            {
                                                                record: [
                                                                    data,
                                                                    ...other,
                                                                ],
                                                            },
                                                            "emojiRecord"
                                                        );
                                                        setEmojiUsedList([
                                                            data,
                                                            ...other,
                                                        ]);
                                                    }
                                                } else {
                                                    if (!isExist) {
                                                        const other =
                                                            emojiUsedList.slice(
                                                                0,
                                                                emojiUsedList.length -
                                                                    1
                                                            );
                                                        addSession(
                                                            {
                                                                record: [
                                                                    data,
                                                                    ...other,
                                                                ],
                                                            },
                                                            "emojiRecord"
                                                        );
                                                        setEmojiUsedList([
                                                            data,
                                                            ...other,
                                                        ]);
                                                    } else {
                                                        const other =
                                                            emojiUsedList.filter(
                                                                (_item) =>
                                                                    _item.id !==
                                                                    item.id
                                                            );
                                                        addSession(
                                                            {
                                                                record: [
                                                                    data,
                                                                    ...other,
                                                                ],
                                                            },
                                                            "emojiRecord"
                                                        );
                                                        setEmojiUsedList([
                                                            data,
                                                            ...other,
                                                        ]);
                                                    }
                                                }
                                            }}
                                        >
                                            <img
                                                src={item.url}
                                                alt={item.name}
                                            />
                                        </li>
                                    ))}
                                </ul>
                            </Scrollbars>
                        </div>
                        <div
                            className={styles.emoji_main2}
                            style={{ display: tabKey === 1 ? "" : "none" }}
                        >
                            <p className={styles.title}>VIP大包子表情</p>
                            <ul className={styles.emoji_ul}>
                                {emojiListVip.map((item) => (
                                    <li
                                        key={item.id}
                                        title={item.name}
                                        onClick={() => {
                                            setIsShowEmoji(false);
                                            // selectEmojiInfo(item);
                                            /**点击大包子表情 会直接发送出去 类型为BIGEMOJI*/
                                            // console.log('大包子: ', item)
                                            const messageData = {
                                                from: profile.userName,
                                                to: id,
                                                content: item,
                                                messageType: "BIGEMOJI",
                                            };
                                            socket.emit(
                                                "send chat message",
                                                messageData
                                            );
                                        }}
                                    >
                                        <img src={item.url} alt={item.name} />
                                    </li>
                                ))}
                            </ul>
                        </div>
                    </div>
                    <div className={styles.emoji_tab}>
                        {["默认", "大包子", "收藏"].map((item, index) => (
                            <span
                                key={index + "_"}
                                className={
                                    tabKey === index ? styles.active : ""
                                }
                                onClick={() => {
                                    setTabKey(index);
                                }}
                            >
                                {item}
                            </span>
                        ))}
                    </div>
                </div>
                <div className={styles.send_file} title="发送文件">
                    <SvgIcon font="icon-a-wenjianjiawenjian" />
                </div>
                <div className={styles.screenshot} title="截图">
                    <SvgIcon font="icon-jiandao" />
                </div>
                <div className={styles.record} title="聊天记录">
                    <SvgIcon font="icon-chat" />
                </div>
            </div>
            <div className={styles.rig}>
                <div className={styles.voice_chat} title="语音聊天">
                    <SvgIcon font="icon-weibiaoti-" />
                </div>
                <div className={styles.video_chat} title="视频聊天">
                    <SvgIcon font="icon-hanhan-01-01" />
                </div>
            </div>
        </div>
    );
};

export default connect(
    (state) => ({
        currentRange: state.currentRangeReducer,
    }),
    { selectEmojiInfo, recordCurrentRange }
)(InputHead);
